<template>
	<view class="ocrVideoContainer">
		<!-- 摄像头组件 -->
		<camera id="myCamera" device-position="back" flash="off" style="width:100%; height:400px;" frame-size="medium">
		</camera>
		<!-- 识别结果 -->
		<view class="title">识别结果：{{ocrData ? ocrData : '无'}}</view>
	</view>
</template>

<script>
	import jsQR from '@/static/js/jsQR.js';
	export default {
		data() {
			return {
				cameraContext: null,
				intervalId: null,
				isResponse: true,
				ocrData: ''
			};
		},
		onReady() {
			this.cameraContext = uni.createCameraContext();
			// 开始定时抓取图像帧
			this.startCapture();
		},
		onUnload() {
			this.isResponse = false
			if (this.listener) {
				this.listener.stop()
				this.listener = null
			}
		},
		methods: {
			startCapture() {
				try {
					this.listener = this.cameraContext.onCameraFrame((frame) => {
						// 一秒24帧 所以要加防抖
						this.$u.throttle(() => {
							const uint8ClampedArray = new Uint8ClampedArray(frame.data);
							const code = jsQR(uint8ClampedArray, frame.width, frame.height);
							if (code) {
								this.ocrData = code.data
							} else {
								console.log("No QR code found.");
							}
						}, 500)
					})
					this.listener.start()
				} catch (err) {
					console.log(err)
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	.ocrVideoContainer {
		width: 100%;
		min-height: 100vh;

		.title {
			font-size: 40rpx;
			text-align: center;
			margin-top: 20rpx;
		}

		.bil {
			display: flex;

			.bliItem {
				width: 100rpx;
				height: 100rpx;
				background-color: #007AFF;
				border-radius: 50%;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #fff;
				margin: 0 20rpx;
			}
		}

		// 固定底部
		.bot {
			display: flex;
			justify-content: space-around;
			align-items: center;
			width: 100%;
			height: 100rpx;
			position: fixed;
			bottom: 0;
			left: 0;
			background-color: #fff;
			z-index: 999;
			padding: 0 20rpx;
			padding-bottom: 60rpx;
		}
	}
</style>